package com.ruoyi.system.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import afu.org.checkerframework.checker.oigj.qual.O;
import afu.org.checkerframework.checker.units.qual.A;
import com.ruoyi.common.Constant;
import com.ruoyi.common.Utils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.Goods;
import com.ruoyi.system.domain.OrderDetail;
import com.ruoyi.system.domain.Shop;
import com.ruoyi.system.domain.vo.GoodsInfo;
import com.ruoyi.system.domain.vo.OrderInfo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.service.IOrderService;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 商品订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-26
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private ISysDictTypeService dictTypeService;
    /**
     * 查询商品订单
     *
     * @param orderId 商品订单主键
     * @return 商品订单
     */
    @Override
    public Order selectOrderByOrderId(Long orderId) {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    /**
     * 查询商品订单列表
     *
     * @param order 商品订单
     * @return 商品订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        List<Order> orderList = orderMapper.selectOrderList(order);
        List<SysDictData> data = dictTypeService.selectDictDataByType(Constant.CONDE_SYS_DELIVERY_STATUS);
        HashMap<String,SysDictData> map= Utils.code2Map(data);
        if(orderList!=null){
            for (int i=0;i<orderList.size();i++) {
                Order tmp = orderList.get(i);
                if(map.containsKey(tmp.getDeliveryStatus())){
                    tmp.setDeliveryText(map.get(tmp.getDeliveryStatus()).getDictLabel());
                }
               List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailByOrderId(tmp.getOrderId());
               tmp.setOrderDetails(orderDetails);
            }
        }
        return orderList;
    }

    private final static String ORDER_ERROR_ARGS = "订单参数错误";
    private final static String ORDER_ERROR_SIGN = "订单签名错误";

    /**
     * 新增商品订单
     *
     * @param orderInfo 商品订单
     * @return 结果
     */
    //@Transactional
    @Override
    public AjaxResult insertOrder(OrderInfo orderInfo) {
        // order.setCreateTime(DateUtils.getNowDate());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(orderInfo.getShopId());
        stringBuilder.append(orderInfo.getTimestamp());
        stringBuilder.append(orderInfo.getTotalAmount());
        stringBuilder.append(orderInfo.getReceivePerson());
        long now = new Date().getTime();
        try {
            long seconds = DateUtils.getTimeDifferenceInSeconds(now, orderInfo.getTimestamp());
            if (seconds > 90) {
                return AjaxResult.error("订单超时,请重新提交");
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return AjaxResult.error("时间戳错误");
        }
        Shop shop = shopMapper.selectShopById(orderInfo.getShopId());
        if (shop == null)
            return AjaxResult.error("不存在的配送地址");
        Long total = 0L;
        List<GoodsInfo> goodsInfos = orderInfo.getGoodsList();
        if (goodsInfos.size() <= 0) {
            return AjaxResult.error("未选择商品");
        }
        for (int i = 0; i < goodsInfos.size(); i++) {
            GoodsInfo info = goodsInfos.get(i);
            stringBuilder.append(info.getSpuId());
            stringBuilder.append(info.getQuantity());
            if (info.getQuantity() == null || info.getSpuId() == null) {
                return AjaxResult.error(ORDER_ERROR_ARGS);
            }
            Goods goods = goodsMapper.selectGoodsBySpuId(info.getSpuId());
            if (goods == null) {
                return AjaxResult.error("不存在的商品");
            }
            if (goods.getSpuStockQuantity() < info.getQuantity()) {
                return AjaxResult.error("库存不足");
            }
            total += goods.getMinSalePrice() * info.getQuantity();
            info.setGoods(goods);
        }
        if (!orderInfo.getTotalAmount().equals(total)) {
            return AjaxResult.error("提交的金额有误");
        }
        String md5Sign = Md5Utils.hash(stringBuilder.toString());
        if (!StringUtils.hasLength(md5Sign)) {
            return AjaxResult.error(ORDER_ERROR_ARGS);
        }
        if (!md5Sign.equals(orderInfo.getSign())) {
            return AjaxResult.error(ORDER_ERROR_SIGN);
        }
        // Date date=new Date(orderInfo.getTimestamp());

        //查询用户积分
        SysUser sysUser = sysUserMapper.selectUserById(orderInfo.getUserId());
        if (sysUser == null) {
            return AjaxResult.error("不存在的用户");
        }
        if (sysUser.getScore().intValue() < total.intValue()) {
            return AjaxResult.error("用户积分不足");
        }
        //开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        String orderNo = now +""+orderInfo.getUserId();
        try {
            int upCount = sysUserMapper.updateUserOrderScore(sysUser.getUserId(), total.intValue());
            if (upCount < 1) {
                throw new Exception("扣除用户积分错误");
            }
            upCount = sysUserMapper.updateUserUseScore(sysUser.getUserId(), total.intValue());
            if (upCount < 1) {
                throw new Exception("扣除用户积分错误");
            }

            Order order = new Order();
            order.setOrderNo(orderNo);
            order.setShopId(orderInfo.getShopId());
            order.setUserId(orderInfo.getUserId());
            order.setTotalAmount(orderInfo.getTotalAmount());
            order.setCreateTime(new Date());
            order.setRemark(orderInfo.getRemark());
            order.setReceivePerson(orderInfo.getReceivePerson());
            orderMapper.insertOrder(order);

            Goods tmpUpdate = new Goods();
            for (int i = 0; i < goodsInfos.size(); i++) {
                GoodsInfo tmp = goodsInfos.get(i);
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(order.getOrderId());
                orderDetail.setSupId(tmp.getSpuId());
                orderDetail.setSupNum(tmp.getQuantity().longValue());
                orderDetail.setSupScore(tmp.getGoods().getMinSalePrice().intValue());
                orderDetailMapper.insertOrderDetail(orderDetail);

                tmpUpdate.setSpuStockQuantity(tmp.getQuantity().longValue());
                tmpUpdate.setSpuId(tmp.getSpuId());
                upCount = goodsMapper.updateUserOrderStock(tmpUpdate);
                if (upCount < 1) {
                    throw new Exception("库存不足");
                }
            }
            dataSourceTransactionManager.commit(transactionStatus);
        } catch (Exception e) {
            //回滚事务
            dataSourceTransactionManager.rollback(transactionStatus);
            return AjaxResult.error(e.getMessage());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("orderNo", orderNo);
        return AjaxResult.success("", map);
    }


    /**
     * 修改商品订单
     *
     * @param order 商品订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        order.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除商品订单
     *
     * @param orderIds 需要删除的商品订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(Long[] orderIds) {
        return orderMapper.deleteOrderByOrderIds(orderIds);
    }

    /**
     * 删除商品订单信息
     *
     * @param orderId 商品订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(Long orderId) {
        return orderMapper.deleteOrderByOrderId(orderId);
    }
}
